// c++ standard lib
#include <iostream>
#include <cstring>
#include <string.h>

// head
#include "UDPClient.h"

using namespace std;

int main(int argc, char**argv)
{
    if (argc != 2)
	{
		printf("Usage: ./client <udpclient port>\n");
		return -1;
	}

	UDPClient* udpclient = new UDPClient(argv[1]);
	// udpclient->Start();
	if (udpclient->InitUDPClient() < 0) {
		cout << "udp client: InitUDPClient() failed" << endl;
		return -1;
	}

	char server_ip[20];
	char username[MAX_USERNAME];
	cout << "Please input server ip: ";
	fgets(server_ip, 20, stdin);
	cout << "Please input your name: ";
	fgets(username, MAX_USERNAME, stdin);
	
	if (!udpclient->Login(username, server_ip))
	{
		cout << "P2PClient::Login() failed" << endl;
		return -1;
	}
	printf("login!\n");

	// first login, update user list
	udpclient->GetPeerList();

	// send current status and usage to user
	cout << "Commands are: \"getu\", \"send\", \"exit\" " << endl;

	// handle user command in a loop
	char command[256];
	while (true)
	{
		fgets(command, 256, stdin);
		if (strlen(command) < 4) { continue; }

		// resolove command
		char comm[10];
		strncpy(comm, command, 4);
		comm[4] = '\0';
		if (strcasecmp(comm, "getu") == 0)
		{
			// get user list
			if (udpclient->GetPeerList())
			{
				printf("Have %d users logined server: \n", udpclient->peerList->currrentSize);
				for (int i = 0; i < udpclient->peerList->currrentSize; i++)
				{
					PEER_INFO* peerInfo = &udpclient->peerList->h_peerList[i];
					printf("Username: %s(%s:%d) \n", peerInfo->username,
						inet_ntoa(*((in_addr*)&peerInfo->addr[peerInfo->addrNum - 1].ip)), peerInfo->addr[peerInfo->addrNum - 1].port);
				}
			}
			else
			{
				cout << "Get user List Failure !" << endl;
			}
		}
		else if (strcasecmp(comm, "send") == 0)
		{
			// resolve username
			char peer[MAX_USERNAME];
			int i = 0;
			for (i = 5;;i++)
			{
				if (command[i] != ' ') {
					peer[i - 5] = command[i];
				}
				else {
					peer[i - 5] = '\0';
					break;
				}
			}

			// resolve msg needed to be sent
			char msg[56];
			strcpy(msg, &command[i+1]);

			// send msg
			if (udpclient->SendText(peer, msg, strlen(msg)))
			{
				cout << "Send ok!" << endl;
			}
			else {
				cout << "Send Failure" << endl;
			}
		}
		else if (strcasecmp(comm, "exit") == 0)
		{
			udpclient->Logout();
			break;
		}
	}
	return 0;
}
